package demo.huodongbaoming.service.impl;

import demo.huodongbaoming.dto.LoginRequest;
import demo.huodongbaoming.dto.RegisterRequest;
import demo.huodongbaoming.dto.UserDTO;
import demo.huodongbaoming.entity.User;
import demo.huodongbaoming.repository.UserRepository;
import demo.huodongbaoming.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public UserDTO register(RegisterRequest registerRequest) {
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(registerRequest.getPassword()); // 实际应用中应该加密
        user.setName(registerRequest.getName());
        user.setEmail(registerRequest.getEmail());
        user.setPhone(registerRequest.getPhone());
        user.setStudentId(registerRequest.getStudentId());
        user.setAdmin(false);
        
        // 保存用户
        User savedUser = userRepository.save(user);
        
        // 转换为DTO并返回
        return convertToDTO(savedUser);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDTO login(LoginRequest loginRequest) {
        // 根据用户名查找用户
        User user = userRepository.findByUsername(loginRequest.getUsername())
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
        
        // 验证密码
        if (!user.getPassword().equals(loginRequest.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        return convertToDTO(user);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDTO getUserById(Long id) {
        User user = getUserEntityById(id);
        return convertToDTO(user);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDTO getUserByUsername(String username) {
        User user = getUserEntityByUsername(username);
        return convertToDTO(user);
    }

    @Override
    @Transactional(readOnly = true)
    public User getUserEntityById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
    }

    @Override
    @Transactional(readOnly = true)
    public User getUserEntityByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new EntityNotFoundException("用户不存在"));
    }
    
    @Override
    @Transactional(readOnly = true)
    public List<UserDTO> getAllUsers() {
        return userRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void deleteUser(Long id) {
        User user = getUserEntityById(id);
        userRepository.delete(user);
    }
    
    @Override
    @Transactional
    public UserDTO updateUser(Long id, String name, String email, String phone, String studentId) {
        User user = getUserEntityById(id);
        
        // 更新用户信息
        user.setName(name);
        user.setEmail(email);
        user.setPhone(phone);
        user.setStudentId(studentId);
        
        // 保存更新
        User updatedUser = userRepository.save(user);
        
        // 转换为DTO并返回
        return convertToDTO(updatedUser);
    }

    @Override
    @Transactional
    public UserDTO setAdminStatus(Long id, boolean isAdmin) {
        User user = getUserEntityById(id);
        user.setAdmin(isAdmin);
        User updatedUser = userRepository.save(user);
        return convertToDTO(updatedUser);
    }

    private UserDTO convertToDTO(User user) {
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        // 不需要手动设置password为null，因为UserDTO中没有password字段
        return userDTO;
    }
} 